import { useSize } from 'ahooks'
import { TableProps } from 'antd'
import React, { HTMLAttributes, useMemo, useRef } from 'react'

interface StretchTableBoxProps extends HTMLAttributes<any> {
  /** 子内容 */
  children?: React.ReactElement
  /** 忽略高度 */
  ignoreHeight?: number[]
  /** 顶部内容 */
  topComponent?: React.ReactElement
  /** 底部内容 */
  bottomComponent?: React.ReactElement
  /** 滚动设置 */
  scroll?: TableProps['scroll']
}

/**
 * 适配表格高度的容器，通过计算表格高度，将表格填充满容器，使用方式：
 * ```tsx
 * <StretchTableBox
 *   className="page-content"
 *   // 额外的组件
 *   topComponent={<Toolbar toolbar={toolbar} />}
 *   // 通过数据传入忽略的高度，包括表头、Top里的工具栏等
 *   ignoreHeight={[toolbar ? 45 : 0, 55]}
 * >
 *   <Table {...tableProps} />
 * </StretchTableBox>
 * ```
 */
export const StretchTableBox = (props: StretchTableBoxProps) => {
  const containerRef = useRef(null)
  const containerSize = useSize(containerRef)

  const {
    topComponent,
    children,
    bottomComponent,
    ignoreHeight,
    scroll,
    ...restProps
  } = props

  const height = containerSize?.height ?? 0

  const scrollHeight = useMemo(() => {
    return height - (ignoreHeight ?? []).reduce((a, b) => a + b)
  }, [height, ignoreHeight])

  const newProps = {
    scroll: {
      y: scrollHeight,
      ...scroll,
    },
  }
  const actualChildren = children
    ? React.cloneElement(children, newProps)
    : children

  return (
    <div {...restProps} ref={containerRef}>
      {topComponent}
      {actualChildren}
      {bottomComponent}
    </div>
  )
}
